/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.rsc.feeds.server;

/**
 *
 * @author arbuckle
 */
import hu.rsc.feeds.client.data.Entry;
import it.sauronsoftware.feed4j.FeedParser;
import it.sauronsoftware.feed4j.bean.Feed;
import it.sauronsoftware.feed4j.bean.FeedHeader;
import it.sauronsoftware.feed4j.bean.FeedItem;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.helpers.DefaultHandler;

public class RssFeedParser extends DefaultHandler {
    private URL url;
    private String source;
    private List<Entry> result;

    public RssFeedParser(String urlstring, String source) throws Exception {
	this.url = new URL(urlstring);
	this.source = source;
    }

    public List<Entry> getPostings() throws Exception {

	this.result = new ArrayList<Entry>();
	try {
	    Feed feed = FeedParser.parse(this.url);
	    //System.out.println("** HEADER **");
	    FeedHeader header = feed.getHeader();
	    //System.out.println("Title: " + header.getTitle());
	    //System.out.println("Link: " + header.getLink());
	    ////System.out.println("Description: " + header.getDescription());
	    //System.out.println("Language: " + header.getLanguage());
	    //System.out.println("PubDate: " + header.getPubDate());

	    // System.out.println("** ITEMS **");
	    int items = feed.getItemCount();
	    for (int i = 0; i < items; i++) {
		FeedItem item = feed.getItem(i);
		Entry e = new Entry();
		e.setTitle(item.getTitle());
		e.setLink(item.getLink().toString());
		e.setSource(this.source);
		e.setDescription(item.getDescriptionAsText());
		e.setHtmlDescription(item.getDescriptionAsHTML());
		e.setDate(item.getPubDate());
		this.result.add(e);
		//System.out.println("Title: " + item.getTitle());
		//System.out.println("Link: " + item.getLink());
		//System.out.println("Plain text description: " + item.getDescriptionAsText());
		//System.out.println("HTML description: " + item.getDescriptionAsHTML());
		//System.out.println("PubDate: " + item.getPubDate());
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return this.result;
    }

}
